#!/usr/bin/env node

/*
 * datadecrypt - data decryptor
 *
 * Copyright (c) 2016 Kenji Urushima (kenji.urushima@gmail.com)
 *
 * This software is licensed under the terms of the MIT License.
 * https://kjur.github.io/jsrsasign/license
 *
 * The above copyright and license notice shall be 
 * included in all copies or substantial portions of the Software.
 * 
 * Please use '-h' option for this script usage.
 * ---------------------------------------------------------
 * DESCRIPTION
 *   This script decrypts a encrypted binary data file with
 *   RSA or RSA-OAEP algorithm.
 *
 * USAGE
 *   % dataencrypt enc.bin plain.txt rsaprv.pem RSA  # with RSA alg
 *   % dataencrypt enc.bin plain.txt rsaprv.pem RSAOAEP  # with RSAOAEP alg
 *   % dataencrypt enc.bin - rsaprv.pem RSA  # output to stdout by '-'
 */

var program = require('commander');
var rs = require('jsrsasign');
var rsu = require('jsrsasign-util');
var path = require('path');

program
  .version('1.0.0 (2016-Nov-05)')
  .usage('[options] <encrypted data file> <output plain file or "-"> <PEM RSA private key file> [RSA|RSAOEAP*>]')
  .description('encrypt data')
  .parse(process.argv);

if (program.args.length < 3)
  throw "wrong number of arguments";

var keyObj, inHex, encHex;
var algName = "RSA";
var keyStr = "";
var inFileOrHex = program.args[0];
var outFile = program.args[1];
var keyFileOrStr = program.args[2];
if (program.args.length > 3) algName = program.args[3];

try {
  keyStr = rsu.readFile(keyFileOrStr);
} catch(ex) {
  keyStr = keyFileOrStr;
}

try {
  inHex = rs.rstrtohex(rsu.readFile(inFileOrHex));
} catch(ex) {
  inHex = inFileOrHex;
}

try {
  keyObj = rs.KEYUTIL.getKey(keyStr);
} catch(ex) {};

if (keyObj instanceof rs.RSAKey && keyObj.isPrivate) {
  var plainStr = rs.KJUR.crypto.Cipher.decrypt(inHex, keyObj, algName);
  if (outFile === "-") {
    process.stdout.write(plainStr);
  } else {
    rsu.saveFile(outFile, plainStr);
    console.log("data decrypted and write to file successfully");
  }
} else {
  console.log("data decryption failed");
}





